<template>
  <div id="appManagePage">
    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="应用名称">
        <a-input v-model:value="searchParams.appName" placeholder="输入应用名称" />
      </a-form-item>
      <a-form-item label="创建者">
        <a-input v-model:value="searchParams.userId" placeholder="输入用户ID" />
      </a-form-item>
      <a-form-item label="生成类型">
        <a-select
          v-model:value="searchParams.codeGenType"
          placeholder="选择生成类型"
          style="width: 150px"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option
            v-for="option in CODE_GEN_TYPE_OPTIONS"
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>
    <a-divider />

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1200 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'cover'">
          <a-image v-if="record.cover" :src="record.cover" :width="80" :height="60" />
          <div v-else class="no-cover">无封面</div>
        </template>
        <template v-else-if="column.dataIndex === 'initPrompt'">
          <a-tooltip :title="record.initPrompt">
            <div class="prompt-text">{{ record.initPrompt }}</div>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'codeGenType'">
          {{ formatCodeGenType(record.codeGenType) }}
        </template>
        <template v-else-if="column.dataIndex === 'priority'">
          <a-tag v-if="record.priority === 99" color="gold">精选</a-tag>
          <span v-else>{{ record.priority || 0 }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'deployedTime'">
          <span v-if="record.deployedTime">
            {{ formatTime(record.deployedTime) }}
          </span>
          <span v-else class="text-gray">未部署</span>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ formatTime(record.createTime) }}
        </template>
        <template v-else-if="column.dataIndex === 'user'">
          <UserInfo :user="record.user" size="small" />
        </template>
        <template v-else-if="column.key === 'action'">
          <div class="action-buttons">
            <a-button type="primary" size="small" @click="editApp(record)"> 编辑 </a-button>
            <a-button
              type="default"
              size="small"
              @click="toggleFeatured(record)"
              :class="['feature-action-btn', { 'featured-btn': record.priority === 99 }]"
            >
              {{ record.priority === 99 ? '取消精选' : '精选' }}
            </a-button>
            <a-popconfirm title="确定要删除这个应用吗？" @confirm="deleteApp(record.id)">
              <a-button danger size="small" class="delete-btn">删除</a-button>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { listAppVoByPageByAdmin, deleteAppByAdmin, updateAppByAdmin } from '@/api/appController'
import { CODE_GEN_TYPE_OPTIONS, formatCodeGenType } from '@/utils/codeGenTypes'
import { formatTime } from '@/utils/time'
import UserInfo from '@/components/UserInfo.vue'

const router = useRouter()

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
    fixed: 'left',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    width: 150,
  },
  {
    title: '封面',
    dataIndex: 'cover',
    width: 100,
  },
  {
    title: '初始提示词',
    dataIndex: 'initPrompt',
    width: 200,
  },
  {
    title: '生成类型',
    dataIndex: 'codeGenType',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    width: 80,
  },
  {
    title: '部署时间',
    dataIndex: 'deployedTime',
    width: 160,
  },
  {
    title: '创建者',
    dataIndex: 'user',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 数据
const data = ref<API.AppVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  try {
    const res = await listAppVoByPageByAdmin({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    message.error('获取数据失败')
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  router.push(`/app/edit/${app.id}`)
}

// 切换精选状态
const toggleFeatured = async (app: API.AppVO) => {
  if (!app.id) return

  const newPriority = app.priority === 99 ? 0 : 99

  try {
    const res = await updateAppByAdmin({
      id: app.id,
      priority: newPriority,
    })

    if (res.data.code === 0) {
      message.success(newPriority === 99 ? '已设为精选' : '已取消精选')
      // 刷新数据
      fetchData()
    } else {
      message.error('操作失败：' + res.data.message)
    }
  } catch (error) {
    console.error('操作失败：', error)
    message.error('操作失败')
  }
}

// 删除应用
const deleteApp = async (id: number | undefined) => {
  if (!id) return

  try {
    const res = await deleteAppByAdmin({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败')
  }
}
</script>

<style scoped>
#appManagePage {
  min-height: 100vh;
  padding: 24px;
  background:
    linear-gradient(180deg, #0a0e27 0%, #1a1f3a 8%, #1e2338 20%, #0f1419 100%),
    radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.25) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.22) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(16, 185, 129, 0.18) 0%, transparent 50%);
  position: relative;
  overflow: hidden;
}

/* 科技感网格背景 */
#appManagePage::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(rgba(59, 130, 246, 0.15) 1px, transparent 1px),
    linear-gradient(90deg, rgba(59, 130, 246, 0.15) 1px, transparent 1px),
    linear-gradient(rgba(139, 92, 246, 0.12) 1px, transparent 1px),
    linear-gradient(90deg, rgba(139, 92, 246, 0.12) 1px, transparent 1px);
  background-size:
    100px 100px,
    100px 100px,
    20px 20px,
    20px 20px;
  pointer-events: none;
  animation: gridFloat 20s ease-in-out infinite;
  opacity: 0.6;
}

@keyframes gridFloat {
  0%,
  100% {
    transform: translate(0, 0);
  }
  50% {
    transform: translate(5px, 5px);
  }
}

#appManagePage > * {
  position: relative;
  z-index: 2;
}

#appManagePage :deep(.ant-divider) {
  border-color: rgba(59, 130, 246, 0.3);
}

/* 表单样式 - 深色主题 */
#appManagePage :deep(.ant-form-item-label > label) {
  color: rgba(255, 255, 255, 0.9);
}

#appManagePage :deep(.ant-input) {
  background: rgba(20, 25, 40, 0.8);
  border-color: rgba(59, 130, 246, 0.3);
  color: rgba(255, 255, 255, 0.9);
}

#appManagePage :deep(.ant-input:hover) {
  border-color: rgba(59, 130, 246, 0.5);
  background: rgba(20, 25, 40, 0.9);
}

#appManagePage :deep(.ant-input:focus),
#appManagePage :deep(.ant-input-focused) {
  border-color: rgba(59, 130, 246, 0.8);
  background: rgba(20, 25, 40, 0.9);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

#appManagePage :deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.4);
}

/* 下拉框样式 - 深色主题 */
#appManagePage :deep(.ant-select-selector) {
  background: rgba(20, 25, 40, 0.8) !important;
  border-color: rgba(59, 130, 246, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

#appManagePage :deep(.ant-select-selector:hover) {
  border-color: rgba(59, 130, 246, 0.5) !important;
  background: rgba(20, 25, 40, 0.9) !important;
}

#appManagePage :deep(.ant-select-focused .ant-select-selector) {
  border-color: rgba(59, 130, 246, 0.8) !important;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2) !important;
}

#appManagePage :deep(.ant-select-selection-item) {
  color: rgba(255, 255, 255, 0.9) !important;
}

#appManagePage :deep(.ant-select-selection-placeholder) {
  color: rgba(255, 255, 255, 0.4) !important;
}

#appManagePage :deep(.ant-select-arrow) {
  color: rgba(255, 255, 255, 0.6);
}

/* 表格样式 - 深色主题 */
#appManagePage :deep(.ant-table) {
  background: transparent;
  color: rgba(255, 255, 255, 0.9);
}

#appManagePage :deep(.ant-table-thead > tr > th) {
  background: rgba(20, 25, 40, 0.8);
  border-color: rgba(59, 130, 246, 0.3);
  color: rgba(255, 255, 255, 0.95);
  font-weight: 600;
}

#appManagePage :deep(.ant-table-tbody > tr > td) {
  background: rgba(15, 20, 35, 0.6) !important;
  border-color: rgba(59, 130, 246, 0.2) !important;
  color: rgba(255, 255, 255, 0.9);
  vertical-align: middle;
}

#appManagePage :deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(30, 40, 60, 0.8) !important;
  border-color: rgba(59, 130, 246, 0.4) !important;
}

#appManagePage :deep(.ant-table-tbody > tr) {
  transition: background-color 0.2s, border-color 0.2s;
}

#appManagePage :deep(.ant-table-tbody > tr:not(:hover) > td) {
  background: rgba(15, 20, 35, 0.6) !important;
}

#appManagePage :deep(.ant-table-tbody > tr.ant-table-row-selected > td) {
  background: rgba(30, 50, 80, 0.8) !important;
}

#appManagePage :deep(.ant-table-tbody > tr.ant-table-row-selected:hover > td) {
  background: rgba(40, 60, 100, 0.9) !important;
}

/* 表格固定列阴影 */
#appManagePage :deep(.ant-table-cell-fix-left),
#appManagePage :deep(.ant-table-cell-fix-right) {
  background: rgba(15, 20, 35, 0.6) !important;
}

#appManagePage :deep(.ant-table-cell-fix-left:hover),
#appManagePage :deep(.ant-table-cell-fix-right:hover) {
  background: rgba(30, 40, 60, 0.8) !important;
}

/* 分页器样式 - 深色主题 */
#appManagePage :deep(.ant-pagination) {
  color: rgba(255, 255, 255, 0.9);
}

#appManagePage :deep(.ant-pagination-item) {
  background: rgba(20, 25, 40, 0.8);
  border-color: rgba(59, 130, 246, 0.3);
}

#appManagePage :deep(.ant-pagination-item a) {
  color: rgba(255, 255, 255, 0.8);
}

#appManagePage :deep(.ant-pagination-item:hover) {
  border-color: rgba(59, 130, 246, 0.6);
  background: rgba(30, 40, 60, 0.9);
}

#appManagePage :deep(.ant-pagination-item:hover a) {
  color: rgba(255, 255, 255, 0.95);
}

#appManagePage :deep(.ant-pagination-item-active) {
  background: rgba(59, 130, 246, 0.8);
  border-color: rgba(59, 130, 246, 0.8);
}

#appManagePage :deep(.ant-pagination-item-active a) {
  color: #fff;
}

#appManagePage :deep(.ant-pagination-prev),
#appManagePage :deep(.ant-pagination-next) {
  background: rgba(20, 25, 40, 0.8);
  border-color: rgba(59, 130, 246, 0.3);
}

#appManagePage :deep(.ant-pagination-prev:hover),
#appManagePage :deep(.ant-pagination-next:hover) {
  border-color: rgba(59, 130, 246, 0.6);
  background: rgba(30, 40, 60, 0.9);
}

#appManagePage :deep(.ant-pagination-prev .ant-pagination-item-link),
#appManagePage :deep(.ant-pagination-next .ant-pagination-item-link) {
  color: rgba(255, 255, 255, 0.8);
  background: transparent;
}

#appManagePage :deep(.ant-pagination-options) {
  color: rgba(255, 255, 255, 0.9);
}

#appManagePage :deep(.ant-pagination-options-size-changer .ant-select-selector) {
  background: rgba(20, 25, 40, 0.8) !important;
  border-color: rgba(59, 130, 246, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

#appManagePage :deep(.ant-pagination-options-size-changer .ant-select-selector:hover) {
  border-color: rgba(59, 130, 246, 0.6) !important;
  background: rgba(30, 40, 60, 0.9) !important;
}

#appManagePage :deep(.ant-pagination-total-text) {
  color: rgba(255, 255, 255, 0.8);
}

/* 表格滚动条样式 */
#appManagePage :deep(.ant-table-body)::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

#appManagePage :deep(.ant-table-body)::-webkit-scrollbar-track {
  background: rgba(20, 25, 40, 0.5);
  border-radius: 4px;
}

#appManagePage :deep(.ant-table-body)::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.5);
  border-radius: 4px;
}

#appManagePage :deep(.ant-table-body)::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.7);
}

/* 确保表格容器背景透明 */
#appManagePage :deep(.ant-table-container) {
  background: transparent;
}

#appManagePage :deep(.ant-table-content) {
  background: transparent;
}

/* 表格空状态 */
#appManagePage :deep(.ant-empty) {
  color: rgba(255, 255, 255, 0.6);
}

#appManagePage :deep(.ant-empty-description) {
  color: rgba(255, 255, 255, 0.6);
}

.no-cover {
  width: 80px;
  height: 60px;
  background: rgba(20, 25, 40, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(255, 255, 255, 0.5);
  font-size: 12px;
  border-radius: 4px;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.prompt-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: rgba(255, 255, 255, 0.8);
}

.text-gray {
  color: rgba(255, 255, 255, 0.5);
}

.feature-action-btn {
  background: rgba(59, 130, 246, 0.15);
  border-color: rgba(79, 152, 246, 0.65);
  color: rgba(224, 242, 254, 0.92);
  box-shadow: 0 2px 10px rgba(59, 130, 246, 0.25);
  transition:
    background 0.25s ease,
    border-color 0.25s ease,
    box-shadow 0.25s ease,
    color 0.25s ease;
}

.feature-action-btn:hover {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.9), rgba(129, 140, 248, 0.9));
  border-color: rgba(129, 140, 248, 0.95);
  color: #fff;
  box-shadow: 0 4px 18px rgba(59, 130, 246, 0.45);
}

.feature-action-btn:focus-visible {
  outline: none;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.35);
}

.featured-btn {
  background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
  border-color: #f59e0b;
  color: white;
  box-shadow: 0 4px 15px rgba(251, 191, 36, 0.3);
}

.featured-btn:hover {
  background: linear-gradient(135deg, #fcd34d 0%, #fbbf24 100%);
  border-color: #fbbf24;
  box-shadow: 0 6px 20px rgba(251, 191, 36, 0.5);
}

.delete-btn {
  background: linear-gradient(135deg, rgba(248, 113, 113, 0.95), rgba(220, 38, 38, 0.95));
  border-color: rgba(239, 68, 68, 0.95);
  color: #fff;
  box-shadow: 0 3px 14px rgba(248, 113, 113, 0.35);
  transition:
    background 0.25s ease,
    border-color 0.25s ease,
    box-shadow 0.25s ease;
}

.delete-btn:hover {
  background: linear-gradient(135deg, rgba(252, 165, 165, 1), rgba(248, 113, 113, 1));
  border-color: rgba(252, 165, 165, 1);
  box-shadow: 0 5px 20px rgba(248, 113, 113, 0.45);
}

.delete-btn:focus-visible {
  outline: none;
  box-shadow: 0 0 0 3px rgba(252, 165, 165, 0.4);
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
  min-width: 0;
}
</style>
